<!-- eslint-disable no-unused-vars -->
<!-- eslint-disable no-undef -->
<template>
	<view>
		<xh-container
			:title="title"
			:hideBack="hideBack"
			:background="titlerBarBackground"
		>
			<view class="container">
				<view class="btn-wrapper">
					<button
						class="search-btn"
						@click="onClickFilter"
						:class="{ searchIsActive: buttonTextActive }"
					>
						{{ buttonText }}
					</button>
					<button
						class="add-btn"
						@click="onClickAdd"
					>
						新增
					</button>
				</view>
				<view class="list-wrapper">
					<view
						class="empty-box"
						v-if="tableData.length === 0"
					>
						<xh-icons name="search"></xh-icons>
					</view>
					<template v-else>
						<view
							class="list-item-wrapper"
							v-for="item in tableData"
							:key="item[rowKey]"
						>
							<view class="list-item-inner-wrapper">
								<view
									class="list-item"
									@click="onClickItem(item)"
								>
									<view
										class="column-item"
										:key="column.key"
										:style="{ width: column.width || '50%' }"
										v-for="column in listColumns"
									>
										<view
											class="label"
											:style="{ width: labelWidth + 'px' }"
											>{{ column.label }}：</view
										>
										<view :class="['text', getTextColorClass(item, column)]">{{
											getTextValue(item, column)
										}}</view>
									</view>
								</view>
								<view
									v-if="isShowDelBtn(item)"
									class="item-delete"
									@click="onClickDelete(item)"
									>删除</view
								>
							</view>
						</view>
					</template>
				</view>
				<slot name="summary"> </slot>
				<uni-pagination
					:current="pageNum"
					:total="total"
					title="标题文字"
					:pageSize="10"
					@change="onPageChange"
				/>
			</view>
		</xh-container>
		<xh-popup
			:title="`${title}筛选`"
			ref="xhPopup"
			@ok="handleClickOk"
		>
			<view style="min-height: 420px">
				<uni-forms
					:modelValue="formData"
					:label-width="80"
				>
					<uni-forms-item
						:label="item.label"
						:name="item.key"
						:key="item.key"
						v-for="item in searchList"
					>
						<uni-datetime-picker
							v-if="item.searchType === 'daterange'"
							v-model="formData.date"
							type="daterange"
						/>
						<xh-data-select
							v-else-if="Array.isArray(item.valueMapList)"
							v-model="formData[item.searchQueryCode || item.key]"
							:localdata="item.valueMapList"
							:placeholder="`请选择${item.label}`"
							@change="handleSelectChange(item)"
						></xh-data-select>
						<xh-data-select
							v-else-if="item.label === '检验编码'"
							v-model="formData.insCode"
							:localdata="showInspectList"
						/>
						<uni-easyinput
							v-else
							type="text"
							v-model="formData[item.key]"
							:placeholder="`请输入${item.label}`"
						/>
					</uni-forms-item>
				</uni-forms>
			</view>
		</xh-popup>
	</view>
</template>

<script>
import { getInspectList } from '@/api/purchase/fabric.js';
import { downloadExcel } from '../../utils/common';
import { getFileName } from '../../api/purchase/fabric';
export default {
	name: 'xh-page-wrapper',
	props: {
		operateBtns: {
			type: [Object, undefined],
			default: undefined,
		},
		labelWidth: {
			type: Number,
			default: 70,
		},
		// list-item显示的字段
		columns: {
			type: Array,
			default: () => [],
		},
		rowKey: {
			type: String,
			default: 'id',
		},
		hideBottomBar: {
			type: Boolean,
			default: true,
		},
		btnText: {
			type: [String],
			default: '',
		},
		titlerBarBackground: {
			type: String,
			default: '#ffffff',
		},
		title: {
			type: String,
			default: '标题',
		},
		hideBack: {
			type: Boolean,
			default: false,
		},
		request: {
			type: Function,
			default: () => [],
		},
		deleteRequest: {
			type: Function,
			default: () => [],
		},
		firstRequest: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			formData: {},
			total: 0,
			buttonText: '筛选',
			pageNum: 1,
			tableData: [],
			// eslint-disable-next-line no-undef
			bottomHeight: getApp().globalData.bottomSafetyHeight + 45 + 'px',
			selectedItem: {},
			showInspectList: [],
		};
	},
	created() {
		if (this.firstRequest) {
			this.fetchTableData();
		}
	},
	computed: {
		buttonTextActive() {
			return Object.values(this.formData).some((val) => val !== '');
		},
		listColumns() {
			return this.columns;
		},
		searchList() {
			const list = this.columns.filter((item) => item.search !== false);
			list.forEach((item, index) => {
				if (item.searchOrder === undefined) {
					item.searchOrder = index;
				}
			});
			list.sort((a, b) => a.searchOrder - b.searchOrder);
			return list;
		},
	},
	methods: {
		isShowDelBtn(item) {
			if (this.operateBtns && item[this.rowKey]) {
				return this.operateBtns.values[item[this.operateBtns.key]].includes(
					'delete'
				);
			}
			return true;
		},
		onClickExport() {
			getFileName().then((res) => {
				downloadExcel(res.msg);
			});
		},
		handleSelectChange(item) {
			if (item.label === '产品名称') {
				this.handleProductChange(item);
			}
		},
		handleProductChange(item) {
			const { valueMapList, searchQueryCode, key } = item;
			const itemKey = searchQueryCode || key;
			const val = this.formData[itemKey];
			const proItem = valueMapList.find((t) => t[itemKey] === val);
			if (proItem) {
				const { productName } = proItem;
				getInspectList(productName).then((res) => {
					const { rows } = res;
					this.showInspectList = this.formatSelectOptions(rows || []);
				});
			} else {
				this.showInspectList = [];
			}
		},
		formatSelectOptions(arr) {
			return arr?.map((item) => ({
				...item,
				text: item.insCode,
				value: item.insCode,
			}));
		},
		onClickItem(item) {
			this.$emit('clickItem', item);
		},
		// 点击删除
		onClickDelete(selectedItem) {
			const id = selectedItem[this.rowKey];
			this.$modal.confirm('确定删除吗？').then(() => {
				this.deleteRequest(id).then(() => {
					this.$modal.msgSuccess('删除成功！');
					this._query();
				});
			});
			this.$emit('clickDelete', selectedItem);
		},
		// 点击编辑
		onClickEdit() {
			if (this.selectedItem[this.rowKey]) {
				this.$emit('clickEdit', this.selectedItem);
			} else {
				this.$modal.msgError('请选择数据');
			}
		},
		// 点击筛选
		onClickFilter() {
			this.$refs.xhPopup.open('top');
		},
		// 点击新增
		onClickAdd() {
			this.$emit('clickAdd');
		},
		_query() {
			this.pageNum = 1;
			this.fetchTableData();
		},
		// 查询数据
		fetchTableData() {
			this.selectedItem = {};
			const { date, ...rest } = this.formData;
			const params = {
				...rest,
				pageNum: this.pageNum,
				pageSize: 10,
			};
			if (Array.isArray(date) && date.length > 1) {
				params.startTime = date[0];
				params.endTime = date[1];
			}
			// eslint-disable-next-line no-undef
			uni.showLoading({
				title: '加载中',
			});
			this.$emit('request', params);
			this.request(params)
				.then((res) => {
					this.tableData = res?.rows || res.data;
					this.total = res?.total;
				})
				.finally(() => {
					// eslint-disable-next-line no-undef
					uni.hideLoading();
				});
		},
		onPageChange({ current }) {
			this.pageNum = current;
			this.fetchTableData();
		},
		handleClickOk() {
			this._query();
			this.$refs.xhPopup.close();
		},
		getOptionItem(item, column) {
			const { valueMapList, key } = column;
			if (valueMapList) {
				return valueMapList.find((mItem) => mItem.value == item[key]);
			}
			return null;
		},
		getTextColorClass(item, column) {
			const oItem = this.getOptionItem(item, column);
			return oItem ? `${oItem.color}-color` : '';
		},
		getTextValue(item, column) {
			const { key } = column;
			const oItem = this.getOptionItem(item, column);
			return oItem ? oItem?.text : item[key] || '-';
		},
	},
};
</script>

<style scoped lang="scss">
.container {
	display: flex;
	flex-direction: column;
	height: 100%;
	position: relative;
	width: 100%;
	overflow: hidden;
	.list-wrapper {
		overflow-y: auto;
		padding: 10px 10px 0 10px;
		overflow-x: hidden;
		flex-grow: 1;
		background: #ffffff;
		.empty-box {
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
}
.search-wrapper {
	display: flex;
}

.search-btn {
	color: $uni-text-color;
}

.searchIsActive {
	color: $uni-color-primary;
}

.popup-title {
	line-height: 45px;
	font-size: 18px;
	font-weight: bold;
	text-align: center;
	height: 45px;
	border-bottom: 1px solid #ccc;
	border-top: 1px solid #ccc;
}

.popup-footer {
	display: flex;

	button {
		flex-grow: 1;
		border-radius: 0;

		&:last-of-type {
			border-left: none;
		}
	}
}

.form-content {
	padding: 10px;
}

.btn-wrapper {
	display: flex;

	button {
		flex-grow: 1;
		border-radius: 0;

		&:last-of-type {
			border-left: none;

			&::after {
				border-left: none;
			}
		}

		&::after {
			border-radius: 0;
		}
	}
}
.list-item-wrapper {
	overflow-x: auto;
	width: calc(100vw - 20px);
	margin-bottom: 10px;
	.list-item-inner-wrapper {
		display: flex;
		width: max-content;
		.item-delete {
			display: flex;
			align-items: center;
			justify-content: center;
			background: $uni-color-error;
			width: 120px;
			color: #ffffff;
			font-weight: bold;
			margin-left: 1px;
			border-radius: 4px;
			margin-left: 8px;
		}
	}
}
.list-item {
	display: flex;
	flex-wrap: wrap;
	background: #ffffff;
	font-size: 14px;
	padding: 10px 10px 0 10px;
	border: 1px solid #a7a7a7;
	border-radius: 4px;
	width: calc(100vw - 20px);
	.column-item {
		display: flex;
		align-items: baseline;
		margin-bottom: 10px;
		.label {
			color: $uni-text-color-grey;
			text-align: right;
		}
		.text {
			color: $uni-text-color;
			flex: 1;
		}
		.success-color {
			color: $uni-color-success;
		}
		.error-color {
			color: $uni-color-error;
		}
	}
}
</style>
